import { ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STChange, STColumn, STComponent, STData, STPage } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map, tap } from 'rxjs/operators';
import { NzFormatEmitEvent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

@Component({
  selector: 'app-organ-organize',
  templateUrl: './organize.component.html',
})
export class OrganOrganizeComponent implements OnInit {
  form: FormGroup;
  nodes = [];

  data: any[] = [];
  loading = false;

  description = '';
  totalCallNo = 0;

  expandKeys = ['0-0'];
  value?: string;
  nodeCampan = [];
  nodeKey = '';
  company = [];

  total: number;
  orgName: string;
  organOwner: string;
  organOwnerPhone: string;
  organOwnerTell: string;
  organOwnerEmail: string;
  standard: string;
  organizeData: any[] = [];

  pageSize = 10;
  pageIndex = 1;
  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
    private nzMessageService: NzMessageService,
  ) {
    this.form = this.fb.group({
      orgName: [null, [Validators.required]],
      orgParent: [null, [Validators.required]],
      organOwner: [undefined, [Validators.required]],
      organOwnerTell: [null, [Validators.required]],
      standard: [null, [Validators.required]],
      organOwnerEmail: [null, [Validators.required]],
      organOwnerPhone: [null, [Validators.required]],
    });
  }

  ngOnInit(): void {
    // 获取上层机构
    this.getTreeMenu();

    // this.getData();
  }

  getTreeMenu(): void {
    // 获取上层机构
    this.http.post('api/organ/getOrganizeTree').subscribe((res) => {
      this.nodes = res.data;
    });
  }

  getData(key: string): void {
    this.loading = true;
    const params = {
      pageNo: this.pageIndex === undefined ? 1 : this.pageIndex,
      pageSize: this.pageSize === undefined ? 1 : this.pageSize,
      parentId: key,
    };

    // 获取上层机构
    this.http.post('api/organ/getOrgainzeSubList', params).subscribe((res) => {
      this.organizeData = res.data.list;
      this.pageIndex = res.data.pageNum;
      this.total = res.data.total;
      this.pageSize = res.data.pageSize;
      this.loading = false;
    });
  }

  add(tpl: TemplateRef<{}>): void {
    this.getCompanyList();

    this.modalSrv.create({
      nzTitle: '新建机构',
      nzContent: tpl,
      nzWidth: 1100,
      nzOnOk: () => {
        this.loading = true;
        // this.http.post('/rule', { description: this.description }).subscribe(() => this.getData());
        this.submit();
      },
    });
  }
  submit(): void {
    const params = {
      organName: this.form.controls.orgName.value,
      parentId: this.form.controls.orgParent.value,
      organOwner: this.form.controls.organOwner.value,
      organOwnerPhone: this.form.controls.organOwnerPhone.value,
      organOwnerTell: this.form.controls.organOwnerTell.value,
      organOwnerEmail: this.form.controls.organOwnerEmail.value,
      standard: this.form.controls.standard.value,
    };

    this.http.post('api/organ/insertOrganize', params).subscribe((res) => {
      if (res.code === 200) {
        this.msg.success('操作成功');
        this.getData(this.nodeKey);
        this.getTreeMenu();
      }
    });
  }
  reset(): void {
    // wait form reset updated finished
    // setTimeout(() => this.getData());
  }
  onExpandChange(e: NzFormatEmitEvent): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadNode(node.key).then((data) => {
        node.addChildren(data);
      });
    }
  }

  loadNode(key: string): Promise<NzTreeNodeOptions[]> {
    return new Promise((resolve) => {
      this.http
        .post('api/organ/getCompanyListByParentId', {
          parentId: key,
        })
        .subscribe((res) => {
          const nodeArray = new Array();
          res.data.forEach((item) => {
            nodeArray.push(
              new NzTreeNode({
                title: item.organName,
                key: item.id,
                children: [],
              }),
            );
          });
          resolve(nodeArray);
        });
    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
    this.getData(event.node.key);
    this.nodeKey = event.node.key;
  }
  edit(id: number, tpl: TemplateRef<{}>): void {
    this.company = this.nodes;
    this.http.post('api/organ/getOrganizeById', { id: id }).subscribe((res) => {
      if (res.code === 200) {
        this.orgName = res.data.organName;
        this.value = res.data.organId;
        this.organOwner = res.data.organOwner;
        this.organOwnerPhone = res.data.organOwnerPhone;
        this.organOwnerTell = res.data.organOwnerTell;
        this.organOwnerEmail = res.data.organOwnerEmail;

        this.modalSrv.create({
          nzTitle: '新建机构',
          nzContent: tpl,
          nzWidth: 1100,
          nzOnOk: () => {
            this.loading = true;
            // this.http.post('/rule', { description: this.description }).subscribe(() => this.getData());
            this.submit();
          },
        });
      }
    });
  }

  onQueryParamsChange(params: NzTableQueryParams): void {
    const { pageSize, pageIndex } = params;
    this.pageIndex = pageIndex;
    this.pageSize = pageSize;
    this.getData(this.nodeKey);
  }

  getCompanyList(): void {
    this.nodeCampan = [];
    // 获取上层机构
    this.http.post('api/organ/getCompanyList').subscribe((res) => {
      res.data.forEach((item) => {
        this.nodeCampan.push(
          new NzTreeNode({
            title: item.organName,
            key: item.id,
            children: [],
          }),
        );
      });
      this.company = this.nodeCampan;
    });
  }

  confirm(id: any, organId: number): void {
    const params = {
      id: id,
      organId: organId,
    };
    this.http.post('api/organ/deleteOrganizeById', params).subscribe((res) => {
      if (res.code === 200) {
        this.msg.success('删除成功');
        this.getData(this.nodeKey);
        this.getTreeMenu();
      }
    });
  }
}
